<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>性感主播在线健身</title>
    <style>
		ul{list-style: none;padding:0;margin:0;}
		.chat-list{position:relative;width:600px;margin:0 auto;}
		.chat-list ul{padding:10px;min-height:200px;max-height:400px;overflow-y:auto;border:1px solid #ddd;}
		.chat-list li{float:left;clear:both;margin:10px 0;padding:5px;line-height:2;border-radius:5px;background-color:#efefef;}
        .chat-list li h4{margin:0;}
		.chat-list li.active{float:right;background-color:#58bc58;color:#fff;}
		.chat-list textarea{display:block;min-height:50px;margin:10px 0;width:100%;box-sizing: border-box;}
		/* .status{display:none;position: absolute;left:50px;bottom:0;right:0;padding:5px 10px;text-align:center;color:#999;} */
		.login{text-align:right;}
	</style>
</head>
<body>
    <h1>性感主播在线健身</h1>
    <div id="chat" class="chat-list">
		<div class="login"><input type="text" name="username" id="username"><button class="btn-login">进入</button><button class="btn-logout">退出</a></div>
		<ul>
		</ul>
		<textarea></textarea>
		<button class="btn-send">提交</button>
		<div class="status"></div>
    </div>
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script>
       /**
        *  客户端WebSocket
            * 连接socket服务器
            * 发送消息给socket服务器
                * 消息格式：{username,msg,date,type}
                    * type
                        * 0：退出聊天室
                        * 1: 进入聊天室
                        * 2：发送消息
        */

        let socket;
        let datalist = [];

        // 1.登录聊天室
        $('.btn-login').on('click',function(){
            // 当连接建立时，禁止二次登陆
            if(socket) return
            // 用户名输入框非空
            if(!$('#username').val().trim()){
                alert('请输入用户名！！！')
                return
            }

            // 1.1 连接WebSocket服务器
            socket = new WebSocket('ws:/localhost:3000/');
            // 1.2 监听socket连接，连接服务器成功后触发open事件
            socket.onopen = function(){
                // 1.3 发送用户登录信息给服务器
                const data = {
                    username:$('#username').val(),
                    msg:'',
                    date:new Date(),
                    type:1
                }
                socket.send(JSON.stringify(data));

                // 禁用输入框
                $('#username').attr('disabled','false')
            }

            // 3. 接受广播：根据type值做出不同响应
            socket.onmessage = (e) =>{

                let data = JSON.parse(e.data);
                // console.log(data);
                switch(data.type){
                    // 退出
                    case 0:
                        $('.status').html(`${data.username}退出了聊天室`);
                        break;
                    // 进入
                    case 1:
                        $('.status').html(`${data.username}进入了聊天室`);
                        break;
                    // 发送消息
                    case 2:
                        datalist.push(data);
                        render(datalist);
                }
            }
            
        })

        // 2. 发送信息
        $('.btn-send').on('click',()=>{
            const data = {
                username:$('#username').val(),
                msg:$('textarea').val(),
                date:new Date(),
                type:2
            }
            socket.send(JSON.stringify(data));
            // 清空输入框并重新聚焦
            $('textarea').val('').focus()
        });


        // 3.退出聊天室
        $('.btn-logout').on('click',()=>{
            const data = {
                username:$('#username').val(),
                msg:'',
                date:new Date(),
                type:0
            }
            socket.send(JSON.stringify(data));
            // 断开连接
            socket.close();
        })
        
        


        function render(data){
            let res = data.map(item=>`<li class="${item.username === username.value ? 'active':''}">
                <h4>${item.username}：</h4>
                <div class="content">${item.msg}</div>
                <time>${formatDate(item.date)}</time>
            </li>`).join('')
            $('ul').html(res)
        }

        function formatDate(date){
            let d = new Date(date);

            let year = d.getFullYear();
            let month = d.getMonth()+1;
            let day = d.getDate();
            let hours = d.getHours();
            let min = d.getMinutes();
            let sec = d.getSeconds();

            hours = hours<10 ? '0' +hours : hours
            min = min<10 ? '0' +min : min
            sec = sec<10 ? '0' +sec : sec

            return `${year}-${month}-${day} ${hours}:${min}:${sec}`
        }
    </script>
</body>
</html>